package com.adnaan.backend.service.storage;

import com.adnaan.backend.common.exception.ServicesException;
import com.adnaan.backend.config.StorageConfig;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Service("qiniuStorageService")
public class QiniuStorageService implements StorageService {
    private final StorageConfig storageConfig;
    private final UploadManager uploadManager;
    private final BucketManager bucketManager;
    private final Auth auth;
    private final String bucket;
    private final String domain;

    public QiniuStorageService(StorageConfig storageConfig) {
        this.storageConfig = storageConfig;
        StorageConfig.Qiniu qiniu = storageConfig.getQiniu();
        this.bucket = qiniu.getBucket();
        this.domain = qiniu.getDomain();
        this.auth = Auth.create(qiniu.getAccessKey(), qiniu.getSecretKey());
        Configuration cfg = new Configuration(Region.autoRegion());
        this.uploadManager = new UploadManager(cfg);
        this.bucketManager = new BucketManager(auth, cfg);
    }

    @Override
    public String getUrl(String fileName) {
        return domain + '/' + fileName;
    }

    @Override
    public String upload(MultipartFile file) {
        if (file.isEmpty()) {
            throw new ServicesException("上传文件为空");
        }
        String fileName = getFileName(Objects.requireNonNull(file.getOriginalFilename()));
        try {
            String token = auth.uploadToken(bucket);
            uploadManager.put(file.getBytes(), fileName, token);
            return fileName;
        } catch (IOException e) {
            log.error("七牛云文件上传失败", e);
            throw new ServicesException("文件上传失败");
        }
    }

    @Override
    public void delete(String fileName) {
        try {
            bucketManager.delete(bucket, fileName);
        } catch (QiniuException e) {
            log.error("七牛云文件删除失败", e);
            throw new ServicesException("文件删除失败");
        }
    }

    private String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        String suffix = fileName.substring(index);
        return UUID.randomUUID().toString().replace("-", "") + suffix;
    }
} 